<template>
  <div>card
    {{jfield}}
    <!--<div-->
      <!--:on-refresh="refresh"-->
      <!--no-data-text="暂无更多数据"-->
      <!--loading-layer-color="position: relative; padding: 0 .55em; color: #999999;font-size:5em"-->
      <!--refresh-layer-color="#4b8bf4"-->
      <!--:on-infinite="infinite"-->
    <!--&gt;-->
      <!--<div class="row">-->
        <!--<template-->
          <!--v-for="card in dataRecord"-->
        <!--&gt;-->
          <!--<van-cell-->
            <!--:key="card.id.value"-->
            <!--class="box-card weui-cells col-md-3 border-radius:4px box-shadow:0 2px 4px rgba（0,0,0,12）,0 0 6px rgba（0,0,0,.04）"-->
          <!--&gt;-->
            <!--<cell-form-preview-->
              <!--:card="card"-->
              <!--:border-intent="false"-->
              <!--:model="model"-->
              <!--:view-id="viewId"-->
              <!--@on-click-card="treeRowClick"-->
              <!--@refresh="refresh_data"-->
            <!--/>-->
          <!--</van-cell>-->
        <!--</template>-->
      <!--</div>-->
    <!--</div>-->

  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import CellFormPreview from '../ctrls/cellFormPreview.vue'
  import {table} from '../api/http'
  import gql from 'graphql-tag'

export default {
  name: 'Card',
  components: {
    CellFormPreview
  },
  props: {
    'domain': { type: Array, default () { return [] } },
    'viewId': { type: Number, default: 0 },
    'limit': { type: Number, default: 10 },
    'offsetStep': { type: Number, default: 10 },
    'context': { type: Object, default () { return {} } },
    'order': { type: String, default: '' } },
    data() {
      return {
        datas: {},
        dataField: null,
        queryFields: null,
        dataRecord: null,
        right: null,
        count: 0,
        data: {
          searchName: '',
          timeInterval: null,
          model: '',
          loading: false,
          list: null,
          total: 0,
          listQuery: {
            page: 1,
            limit: 20
          },
          multipleSelection: [],
          delVisible: false,
          order: '__last_update desc',
          tablePage: {
            currentPage: 1,
            pageSize: 25
          },
          response: {},
          result: {},
          record: {},
          groupRecord: [],
          groupby: [],
          groupResult: [],
          fields: {},
          canUnlink: false,
          todelid: 0 // 删除使用的临时变量
        },
        toolbar: {
          custom: true,
          zoom: true,
          refresh: {query: this.reload},
          buttons: [{name: '新增', code: 'newRecord', visible: true, icon: 'fa fa-plus'}, {
            name: '导出',
            code: 'exportDataEvent',
            visible: true,
            icon: 'fa fa-export'
          }],
          slots: {buttons: 'toolbar_buttons'}
        }
      }
    },
    apollo: {
      jfields: {
        query: gql`query qdv($model:String){
          jfields:allJfield(model:$model)
          }`,
        variables() {
          return {
            model: this.data.model
          }
        },
        skip() {
          return !this.data.model
        }
      },
      dataField: {
        query: gql`query qdv($domain:String){
          dataField:allMobileModel(domain:$domain) {
              fieldsListIds{
                name
                id
                fieldDescription
                help
                type:ttype
              }
            }
          }`,
        variables() {
          return {
            domain: JSON.stringify([['model', '=', this.data.model]])
          }
        },
        skip() {
          return !this.data.model
        }

      },
      dataRecord: {
        query: gql`query qdv($model:String,$domain:String!,$queryFields:[String],$order:String,$limit:Int,$offset:Int){
                   dataRecord:allRecord(model:$model,domain:$domain,fields:$queryFields,order:$order,limit:$limit,offset:$offset){
            value
          }
          count:count(model:$model,domain:$domain)
         }`,
        variables() {
          return {
            model: this.data.model,
            queryFields: this.queryFields,
            offset: ((this.data.tablePage.currentPage - 1) * this.data.tablePage.pageSize) || 0,
            domain: JSON.stringify(this.domain),
            order: this.data.order,
            limit: this.data.tablePage.pageSize
          }
        },
        skip() {
          return !(this.data.model && this.queryFields)
        }
      },
      count: {
        query: gql`query qdv($model:String,$domain:String){
                   count:count(model:$model,domain:$domain)
         }`,
        variables() {
          return {
            model: this.data.model,
            domain: JSON.stringify(this.domain)
          }
        },
        skip() {
          return !(this.data.model)
        }
      },
      right: {
        query: gql`query qdv($model:String){
      right:access(model:$model)
      }`,
        variables() {
          return {
            model: this.data.model
          }
        },
        skip() {
          return !(this.data.model)
        }
      }
    },
    computed: {
      domain: function () {
        let d = []
        if (this.$refs.filter) d = this.$refs.filter.domain
        if (this.data.searchName && this.data.searchName.length > 0) {
          let v = []
          v.push(['name', 'ilike', this.data.searchName])
          v.concat(d)
          return v
        } else return d
      }
    },

    watch: {
      $route(to, from) {
        // 刷新参数放到这里里面去触发就可以刷新相同界面了
        let self = this
        self.data.model = to.params.model
        self.data.offset = 0
        this.data.record = []
        this.data.groupby = []
      },
      'data.groupby'(to, from) {
        let groupby = to
        if ((groupby.length > 0) && (groupby !== from)) {

        }
      },
      dataField: function (to, from) {
        this.refersh()
      },
      jfields(to, from) {
        this.refersh()
      }

    },
    mounted: function () {
      this.data.model = this.$route.params.model
      let self = this
      self.app_root.model = self.$route.params.model
      self.offset = 0
    },
    methods: {
      refersh() {
        if (this.dataField && this.jfields) {
          let val = []
          let other = []
          let dfields = (this.dataField[0] && this.dataField[0].fieldsListIds) ? this.dataField[0].fieldsListIds.map(x => x.name) : []
          for (let item of Object.keys(this.jfields)) {
            if (websiteField.indexOf(item) >= 0) {
              this.website = true
              // } else if (baseField.indexOf(item) >= 0) {
              // this.website = true
            } else if (ratingField.indexOf(item) >= 0) {
              this.rating = true
            } else if (msgField.indexOf(item) >= 0) {
              this.mail = true
            } else if (dfields.indexOf(item) >= 0 || item.name === 'id' || item.name === 'display_name') {
              val.push(item)
            } else {
              let v = {}
              v[item] = this.jfields[item]
              other.push(v)
            }
          }
          this.queryFields = val
          this.otherFields = other
        }
      },
      reload() {
        this.$apollo.queries.dataRecord.refetch()
      },
      refetch() {
        this.$apollo.queries.dataField.refetch()
        this.$apollo.queries.dataRecord.refetch()
      },
      switchData(id) {
        let data = this.datas[id]
        if (!data) {
          data = {
            timeInterval: null,
            model: id,
            loading: false,
            list: null,
            total: 0,
            listQuery: {
              page: 1,
              limit: 20
            },
            multipleSelection: [],
            delVisible: false,
            order: '__last_update desc',
            tablePage: {
              currentPage: 1,
              pageSize: 25
            },
            response: {},
            result: {},
            record: {},
            groupRecord: [],
            domain: [],
            groupby: [],
            groupResult: [],
            fields: {},
            canUnlink: false,
            todelid: 0 // 删除使用的临时变量
          }
          this.datas[id] = data
        }
        this.data = data
      },

      sortChange: function (column, property, order) {
        // console.debug(column, property, order)
        switch (column.order) {
          case 'asc':
            this.data.order = column.prop + ' asc'
            break
          case 'desc':
            this.data.order = column.prop + ' desc'
            break
          default:
            this.data.order = ''
        }
      },
      fmkdata: function (record) {
        let val = []
        for (let i in record) {
          let value = record[i]
          value['treeNode'] = false
          val.push(value)
        }
        return val
      },
      fmkGroup: function (self, record) {
        let val = []
        for (let i = 0; i < record.length; i++) {
          let item = record[i]
          val.push({
            treeNode: true,
            name: item[self.data.groupby[0]][1],
            count: item[self.data.groupby[0] + '_count'],
            children: [],
            hasChild: true,
            domain: item['__domain']
          })
        }
        return val
      },
      handlePageChange({currentPage, pageSize}) {
        this.data.tablePage.currentPage = currentPage
        this.data.tablePage.pageSize = pageSize
      },
      loadChildrenMethod({row}) {
        // 异步加载子节点
        // console.info(row)
        let self = this

        return new Promise(resolve => {
          table(self.data.model, {
            domain: row.domain,
            order: self.data.order,
            limit: self.data.tablePage.pageSize,
            offset: ((self.data.tablePage.currentPage - 1) * self.data.tablePage.pageSize) || 0
          }).then(function (response) {
            if (!response) {
              return
            }
            let result = response.result
            // self.tablePage.totalResult = self.result.count
            let record = result.record

            row.children = self.fmkdata(record)
            self.data.loading = false
            clearInterval(self.data.timeInterval)
            resolve(row.children)
          }, function (error) {
            console.error(error)
            self.data.loading = false
            clearInterval(self.data.timeInterval)
          })
        })
      },
      toolbarButtonClickEvent({code}, event) {
        switch (code) {
          case 'newRecord':
            this.newRecord(code)
            break
          case 'exportDataEvent':
            this.exportDataEvent(code)
            break
        }
      },
      newRecord() {
        this.$router.push({
          name: 'NewForm',
          params: {
            model: this.data.model,
            id: 0,
            title: this.data.model + ':New'
          }
        })
      },
      toBuffer(wbout) {
        let buf = new ArrayBuffer(wbout.length)
        let view = new Uint8Array(buf)
        for (let index = 0; index !== wbout.length; ++index) view[index] = wbout.charCodeAt(index) & 0xFF
        return buf
      },
      exportDataEvent() {
        let table = this.$refs.xTable.$el.querySelector('.body--wrapper>.vxe-table--body')
        let book = XLSX.utils.book_new()
        let sheet = XLSX.utils.table_to_sheet(table)
        XLSX.utils.book_append_sheet(book, sheet)
        let wbout = XLSX.write(book, {bookType: 'csv', bookSST: false, type: 'binary'})
        let blob = new Blob([this.toBuffer(wbout)], {type: 'application/octet-stream'})
        // 保存导出
        FileSaver.saveAs(blob, '数据导出.csv')
      },
      doedit: function (index, item) {
        this.$router.push({
          name: 'EditForm',
          params: {
            model: this.data.model,
            id: item.value.id,
            title: item.value.display_name
          }
        })
      },
      handleDelete: function (index, item) {
        this.data.todelid = item.value.id
        this.data.delVisible = true
      }, // 确定删除
      deleteRow() {
        let self = this
        unlink(this.data.model, {activeId: self.data.todelid}).then(
          function () {
            self.$message.success('删除成功')
            self.data.delVisible = false
            self.reload()
          },
          function () {
          }
        )
      },
      handleSelectionChange(val) {
        this.data.multipleSelection = val
        if (this.data.multipleSelection.length > 0) this.data.canUnlink = right.unlink
        else this.data.canUnlink = false
      },
      colspanMethod({row, rowIndex, column, columnIndex, data}) {
        // console.info(row, rowIndex, column, columnIndex, data)
        if (rowIndex < 0 || columnIndex < 0) {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
        if (row.treeNode) {
          if (columnIndex === 1) {
            return {
              rowspan: 1,
              colspan: this.data.mcols.length + 2
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        } else {
          return {
            rowspan: 1,
            colspan: 1
          }
        }
      }
    }, // 第一次进入或从其他组件对应路由进入时触发
    beforeRouteEnter(to, from, next) {
      const model = to.params.model
      if (model) {
        next(instance => instance.switchData(model))
      } else {
        next(new Error('未指定ID'))
      }
    },
    // 在同一组件对应的多个路由间切换时触发
    beforeRouteUpdate(to, from, next) {
      const model = to.params.model
      if (model) {
        this.switchData(model)
        next()
      } else {
        next(new Error('未指定ID'))
      }
    }

  }
</script>

<style scoped lang="scss">

</style>
